package com.interview.javabase.algorithm.hand.可重入锁;

/**
 * 手写重入锁
 *
 * @author zhangshguang
 * @date 2020/07/27
 */
public class HandReentrant {

    Thread lockBy = null;

    private boolean isLocked = false;

    volatile int count = 0;

    public synchronized void lock() throws InterruptedException {

        Thread thread = Thread.currentThread();
        while (isLocked && lockBy != thread) {
            this.wait();
        }
        isLocked = true;
        count++;
        lockBy = thread;
    }

    public synchronized void unlock() {
        Thread thread = Thread.currentThread();
        if (lockBy == thread) {
            count--;
            if (count == 0) {
                notifyAll();
                //释放锁
                isLocked = false;
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {

        HandReentrant handReentrant = new HandReentrant();

        new Thread(() -> {
            try {
                handReentrant.lock();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("测试11");

            int index = 1;
            while (true) {
                try {
                    handReentrant.lock();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("第" + (++index) + "次获取锁，这个锁是：" + handReentrant.getClass());
                handReentrant.unlock();
                if (index == 100) {
                    break;
                }
            }

            handReentrant.unlock();
        }).start();


        new Thread(() -> {

            System.out.println("测试44-----------------------------------");
            try {
                handReentrant.lock();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("测试43");

            handReentrant.unlock();
        }).start();


    }

}
